// pages/licencePlate/licencePlate.js
const app = getApp()
var request = require("../../utils/request.js");
var log = require("../../utils/log.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
let addFlag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    titleText: '我的车辆',
    statusBarHeight: app.globalData.statusBarHeight,
    windowHeight: 0,
    scrollViewHeight: 0,
    inputLen: 8,
    isFocus: true,
    carNo: '',
    translateSpace: 0,
    inputType: 1, // 车牌输入类型，1简称，2数字或者字母,
    showPlateInput: false,
    activeIptIndex: -1,
    isAndroid: false,
    verifyLoginDialog: false,
    carNumList: [],
    carNumberIndex: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let tabIndex = options.tabIndex;
    let tabs = that.data.tabs;
    if (wx.getSystemInfoSync().platform == 'android') {
      this.setData({
        isAndroid: true
      })
    }
    if (tabIndex != '' && tabIndex != undefined) {
      for (let i = 0; i < tabs.length; i++) {
        if (i == tabIndex) {
          tabs[i].select = true
        } else {
          tabs[i].select = false;
        }
      }
      that.setData({
        tabs: tabs,
        tabIndex: tabIndex
      })
      //根据tab切换获取当前列表
      if (tabIndex == 0) {
        that.getSubscribeList();
      } else if (tabIndex == 1) {
        that.getChargeList();
      } else {
        that.getCompletedList();
      }
    }
    that.setData({
      scrollViewHeight: wx.getSystemInfoSync().windowHeight - that.data.statusBarHeight - 44
    })
  },
  onShow() {
    let token = wx.getStorageSync('token');
    if (token) {
      this.getCarNumList()
    } else {
      this.setData({
        verifyLoginDialog: true
      })
    }

  },
  verifyLogin() {
    this.getCarNumList()
  },
  //返回上一个页面
  back() {
    wx.navigateBack({ //返回
      delta: 1,
      fail(err) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })
  },
  addCar() {
    wx.navigateTo({
      url: 'add/add',
    })
  },
  /**
   * 查询车牌列表
   */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        let data = res.data
        console.log(res);
        if (data.code == 200) {
          let list = data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i]['select'] = true
              } else {
                list[i]['select'] = false
              }
            }
          }
          that.setData({ 
            list,
            carNumList:list
           })
        }
      })
  },

  /**
   * 删除车牌
   * @param {*} event 
   */
  deleteCarNum(event) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该车牌号吗？',
      showCancel: true, //是否显示取消按钮
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          let id = event.currentTarget.dataset.customerid;
          let url = '/customer/car/deleteCustomerCar'
          let params = {
            id: id
          }
          request.http(url, 'POST', params)
            .then((res) => {
              // log.info('接口' + url + ':' + JSON.stringify(res.data))
              let data = res.data
              if (data.code == 200) {
                Toast.success('删除成功');
                that.getCarNumList();
              }
            })
        }
      },

    })
  },
  /**
   * 设置value
   * @param {*} e 
   */
  setValue: function (e) {
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
  },
  /**
   * 自定义键盘点击
   * @param {*} e 
   */
  inputChange(e) {
    let that = this;
    let iptValue = that.data.iptValue;
    let value = e.detail;
    let keyBoardType = that.data.keyBoardType;
    that.setData({
      iptValue: iptValue + value
    })
    if (keyBoardType == 1) {
      that.setData({
        keyBoardType: 2
      })
    }
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘隐藏事件
   */
  handleHiddenCarPlate() {
    this.setData({
      showPlateInput: false,
      activeIptIndex: -1
    })
  },
  /**
   * 键盘输入操作
   * @param {*} e 
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      Toast('请输入正确车牌号');
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   * @param {*} e 
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加车牌号
   */
  addCarNumber() {
    if (addFlag) {
      return
    }
    let that = this;
    let carNo = that.data.carNo;
    if (!that.isCarPlate(that.data.carNo)) {
      Toast('请输入正确车牌号');
      return;
    }
    addFlag = true
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        log.info('接口' + url + ':' + JSON.stringify(res.data))
        let data = res.data
        if (data.code == 200) {
          Toast.success('添加成功');
          that.setData({ carNo: '' })
          that.getCarNumList();
          that.handleHiddenCarPlate()
        } else {
          // Toast.success('添加失败，请稍后重试！');
        }
        addFlag = false
      }).catch((errMsg) => {
        addFlag = false
      });
  },
  /**
   * 输入车牌号
   * @param {*} e 
   */
  onFocus: function (e) {
    console.log(e);
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: that.data.carNo.length
    });
  },
    /**
   * 选择车牌号
   */
  selectCar(e) {
    let index = e.currentTarget.dataset.index
    let carList = this.data.carNumList
    for (var i = 0; i < carList.length; i++) {
      carList[i]['select'] = false
    }
    carList[index]['select'] = true
    this.setData({
      carNumList: carList,
      carNumberIndex: index
    })
  },

  // 微信支付分停车
  async goWxFreePay() {
    let carNumber = this.data.carNumList.length != 0? this.data.carNumList[this.data.carNumberIndex].carNumber : null;
    console.log(carNumber);
    if(!carNumber) {
      wx.showToast({
        icon:'none',
        title: '请先添加车牌号',
      })
      return false
    }
    const { data:res } = await request.http(
      '/wchart/car/query', 
      'GET', 
      { carNumber },
    )
    console.log(res);
    wx.navigateToMiniProgram({
      appId: 'wxbcad394b3d99dac9',
      path: '/pages/auth-creditpay/auth-creditpay',
      extraData: {
        mchid: res.data.mchid,
        sub_mchid: res.data.sub_mchid,
        openid: res.data.openid,
        plate_number: res.data.plate_number,
        plate_color: res.data.plate_color,
        trade_scene: res.data.trade_scene
      },
      success(resp) {
        console.log(resp);
      },
      fail(err) {
        console.log(err);
      },
    }); 
  },

})